package com.dep.service.impl;

import com.dep.common.ResponseData;
import com.dep.dto.req.StaffInsertReq;
import com.dep.dto.req.StaffReq;
import com.dep.dto.resp.DepartmentResp;
import com.dep.dto.resp.StaffResp;
import com.dep.entity.Department;
import com.dep.entity.Staff;
import com.dep.mapper.DepartmentMapper;
import com.dep.mapper.StaffMapper;
import com.dep.service.StaffService;
import com.dep.util.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StaffServiceImpl implements StaffService {

    @Resource
    private StaffMapper staffMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    public ResponseData insertStaff(StaffInsertReq req) throws InvocationTargetException, IllegalAccessException {
        //判断部门是否存在
        Department department = departmentMapper.selectByPrimaryKey(req.getDepId());
        if(StringUtils.isEmpty(department)){
            return ResponseData.fail("部门不存在");
        }
        //判断编号是否一样
        long countNo = staffMapper.selectByStaffNo(req.getStaffNo());
        if(countNo > 0){
            return ResponseData.fail("员工编号已存在");
        }

        Staff staff = new Staff();
        BeanUtils.copyProperties(staff,req);
        staff.setLnductionAt(DateUtil.parseDateStr(req.getLnductionAtStr()));

        staff.setCreatedAt(new Date());
        int count = staffMapper.insertSelective(staff);

        if(count > 0 ){
            return ResponseData.success();
        }
        return ResponseData.fail();
    }

    @Override
    public ResponseData<PageInfo<StaffResp>> findStaffPage(StaffReq req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<StaffResp> list = staffMapper.findPage(req);
        return ResponseData.success(new PageInfo<>(list));
    }
}
